"""
---------------------------------------------------------------------
- File: login.py
- Date: 2025/11/18
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 登录接口
---------------------------------------------------------------------
"""

from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.security import OAuth2PasswordRequestForm
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession

from app.core.dependency import get_async_session, create_access_token
from app.core.dependency import get_current_user
from app.core.response import ResponseBase, ResponseSuccess
from app.core.security import verify_password
from app.models.system import Users
from app.schemas.enums import UserStatusEnum
from app.schemas.system.login import UserLogin, Token, AuthenticatedUser
from app.schemas.system.users import UserWithRoles

login_router = APIRouter(prefix="/system/login", tags=["系统管理-登录"])


@login_router.post("/", summary="用户登录", response_model=UserLogin)
async def login(
    request: Request,
    form_data: OAuth2PasswordRequestForm = Depends(),
    session: AsyncSession = Depends(get_async_session),
) -> UserLogin:
    """
    用户登录--返回token
    """
    # 查询用户信息
    statement = select(Users).where(Users.user_no == form_data.username)  # 这里的username是user_no
    result = await session.exec(statement)
    user: Users | None = result.first()
    if not user:
        raise HTTPException(status_code=400, detail="用户名或密码错误")
    if not verify_password(form_data.password, user.hash_password):
        raise HTTPException(status_code=400, detail="用户名或密码错误")
    if user.status == UserStatusEnum.DISABLED.value:
        raise HTTPException(status_code=403, detail="用户已被禁用")

    # 添加用户信息到request.state
    request.state.auth_user = AuthenticatedUser(id=user.id, user_no=user.user_no, user_name=user.user_name)
    # 生成token
    access_token = await create_access_token(data={"user_no": user.user_no})
    token = Token(access_token=access_token, token_type="bearer")
    user_login = UserLogin(access_token=access_token, token_type="bearer", code=200, message="成功", data=token)
    return user_login


@login_router.get("/get_user_info", summary="获取当前登录用户信息", response_model=ResponseBase[UserWithRoles])
async def get_user_info(user: Users = Depends(get_current_user)):
    """
    获取当前登录用户信息
    """
    return ResponseSuccess(data=user)
